<template>
  <el-form
    :label-position="labelPosition"
    label-width="60px"
    :model="loginInfo"
    :rules="rules"
    style="max-width: 460px"
    ref="formRef"
  >
    <el-form-item label="账号" prop="account">
      <el-input v-model="loginInfo.account" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginInfo.password" />
    </el-form-item>
    <div style="margin-left: 20px; font-size: 12px">超级管理员账号：admin； 密码：123</div>
    <div style="margin-left: 20px; font-size: 12px">普通用户账号：demo； 密码：123</div>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { ElForm, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useLoginStore } from '../../../stores/login/index'
import type { ILogin } from '@/type/index.d'
import { localCache } from '@/utils/storage'
import { ACCOUNT, PASSWORD } from '@/global/constants'

const labelPosition = ref('right')
const loginStore = useLoginStore()

const loginInfo = reactive<ILogin>({
  account: localCache.getStorage(ACCOUNT) ?? 'admin',
  password: localCache.getStorage(PASSWORD) ?? '123',
})

const rules = reactive<FormRules>({
  account: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '长度应在2-10之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '长度应在2-10之间', trigger: 'blur' },
  ],
})

const formRef = ref<InstanceType<typeof ElForm>>()

function loginAction(isRememberPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      loginStore.loginAction(loginInfo).then((res) => {
        if (isRememberPwd) {
          localCache.setStorage(ACCOUNT, loginInfo.account)
          localCache.setStorage(PASSWORD, loginInfo.password)
        } else {
          localCache.removeStorage(ACCOUNT)
          localCache.removeStorage(PASSWORD)
        }
      })
    } else {
      ElMessage.error('请输入正确的格式')
      return
    }
  })
}

// 执行登陆逻辑
defineExpose({
  loginAction,
})
</script>
